<?php

namespace App\Libs;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Parser;

class Jwt
{
    private $salt;

    public function __construct()
    {
        $this->salt = 'fuckyou.fb-9520';
    }


    public function Encode($arr)
    {
        $signer = new Sha256();
        $builder = new Builder();
        $builder->setHeader('alg', 'HS256');
        foreach ($arr as $key => $value) {
            $builder->set($key, $value);
        }
        $builder->sign($signer, $this->salt);
        $token = strval($builder->getToken());
        return $token;
    }


    function checkToken($token)
    {
        $token = (new Parser())->parse((string)$token);
        $signer = new Sha256();
        $result = $token->verify($signer, $this->salt);
        //先验证签名再验证有效期
        if ($result) {
            $exp = $token->getClaim('exp');
            if ($exp <= time()) {
                return false; //超时
            } else {
                return true;
            }
        } else {
            //签名错误
            return false;
        }
    }
}
